<template>
  <div class="replace-box">
    <iu-header>
      <template #left>
        <x-icon
          @click="back"
          type="ios-arrow-back"
          size="21"
          fill="#fff"
        ></x-icon>
      </template>
      <template #title>更换执行</template>
      <template #right>
       <div v-focusable  @click="backToHomepage">
          <iconSvg name="home" w="20px" h="22px" class="right_icon"></iconSvg>
        </div>
      </template>
    </iu-header>
    <div class="content">
      <div class="cate-nfo">
        <div class="info-list" v-if="detail.record">
          <div class="info-list-item">
            <div class="info-title">设备名称：</div>
            <div class="info-value">{{ detail.record.deviceName || "" }}</div>
          </div>
          <div class="info-list-item">
            <div class="info-title">设备编号：</div>
            <div class="info-value">{{ detail.config.deviceCode || "" }}</div>
          </div>
          <div class="info-list-item">
            <div class="info-title">所在部门：</div>
            <div class="info-value">
              {{ departmentName }}
              <span v-if="!isLastLevel">
                / {{ detail.config.departmentName || "" }}
              </span>
            </div>
          </div>
          <div class="info-list-item" v-if="detail.record.componentName">
            <div class="info-title">部件名称：</div>
            <div class="info-value">
              {{ detail.record.componentName || "" }}
            </div>
          </div>
          <div class="info-list-item" v-if="detail.record.stockCatName">
            <div class="info-title">部件规格：</div>
            <div class="info-value">{{ detail.record.stockCatName || "" }}</div>
          </div>
          <div class="info-list-item">
            <div class="info-title">质保时长：</div>
            <div class="info-value">
              {{ detail.config.replaceCycle || "" }}
              {{ replaceCycleUnitText[detail.config.replaceCycleUnit || 0] }}
            </div>
          </div>
          <div class="info-list-item">
            <div class="info-title">更换状态：</div>
            <div class="info-value">
              {{ detail.record.residueTime > 0 ? "剩余" : "逾期" }}
              {{
                detail.record.residueTime > 0
                  ? detail.record.residueTime
                  : -detail.record.residueTime
              }}
              天
              <span
                style="margin-left:8px"
                :class="'status' + detail.record.status"
              >
                {{ detail.record.status | statusText }}
              </span>
            </div>
          </div>
        </div>
        <div class="info-list">
          <li class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">投入使用时间</span>
            </div>
            <div class="contentRight border" @click="selectTime('onlineTime')">
              <span v-if="replaceForm.onlineTime">
                {{ replaceForm.onlineTime | formatDate("YYYY-MM-DD") }}
              </span>
              <span v-else style="color:gray;font-size:14px">
                选择投入使用时间
              </span>
              <span class="iconfont icon2" style="font-size:14px">&#xe669;</span>
            </div>
          </li>
          <div class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">质保时长</span>
            </div>
            <div class="contentRight">
              <input
                type="text"
                v-model.number="replaceForm.dueTime"
                placeholder="请输入质保时长"
                maxlength="8"
                style="width:65%"
              />
              <select
                class="iu-select"
                style="width: 30%;"
                required
                v-model="replaceForm.dueTimeUnit"
              >
                <option :value="1" selected>天</option>
                <option :value="2">月</option>
                <option :value="3">年</option>
              </select>
            </div>
          </div>
          <div class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">更换结果</span>
            </div>
            <div class="contentRight">
              <select
                class="iu-select"
                required
                v-model="replaceForm.replaceResult"
              >
                <option :value="'更换完成'" selected>更换完成</option>
                <option :value="'无需更换'">无需更换</option>
                <option :value="'延后更换'">延后更换</option>
              </select>
            </div>
          </div>
          <div
            class="contentList"
            v-if="replaceForm.replaceResult === '延后更换'"
          >
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">延后日期</span>
            </div>
            <div class="contentRight border" @click="selectTime('endTime')">
              <span v-if="replaceForm.endTime">
                {{ replaceForm.endTime | formatDate("YYYY-MM-DD HH:mm") }}
              </span>
              <span v-else style="color:gray;font-size:14px">
                选择延后日期
              </span>
              <span class="iconfont icon2" style="font-size:14px">&#xe669;</span>

            </div>
          </div>
          <div class="contentList" >
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">更换人</span>
            </div>
            <div class="contentRight">
              <fz-people
                class="changeDep"
                :peopleId="curDepartment.departmentId"
                :leader="replaceForm.operator"
                :name="'选择更换人'"
                :peopleData="peopleData"
                @selectPeople="getOperator"
                ref="people"
                :style="{
                  color: selectPeopleIdshow
                    ? '#fff!important'
                    : '#6f6f77!important'
                }"
              >
              </fz-people>
            </div>
          </div>

          <div class="contentList full">
            <div class="contentLeft">
              <span class="notNull">&nbsp;</span>
              <span class="contentLeftFont">描述</span>
            </div>
            <div class="contentRight">
              <textarea
                name="userQuestion"
                v-model="replaceForm.remark"
                placeholder="请输入描述"
                class="userQuestion"
                maxlength="200"
              ></textarea>
            </div>
          </div>
        </div>

        <div class="info-list">
          <div class="contentList upload">
            <div class="contentLeft">
              <span class="contentLeftFont">更换拍照：</span>
            </div>
            <div class="contentRight cancelPos ">
              <upload
                :file-list="fileList"
                :loading="loading"
                :max-count="10"
                :max-size="10 * 1024 * 1024"
                @oversize="oversize"
                @overcount="overcount"
                :file-stream="true"
                @delete="deleteList"
                @afterRead="afterRead"
              ></upload>
            </div>
          </div>
        </div>
        <div class="info-list">
          <div class="contentRight cancelPos ">
            <x-switch
              title="是否上报工单"
              :value-map="[0, 1]"
              v-model="replaceForm.isWorkSheet"
            ></x-switch>
          </div>
          <div class="contentList" v-if="replaceForm.isWorkSheet">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">负责人</span>
            </div>
            <div class="contentRight">
              <fz-people
                class="changeDep"
                :peopleId="curDepartment.departmentId"
                :leader="replaceForm.workSheetLeader"
                :name="'选择负责人'"
                :peopleData="peopleData"
                @selectPeople="getPeople"
                ref="people"
                :style="{
                  color: selectPeopleIdshow
                    ? '#fff!important'
                    : '#6f6f77!important'
                }"
              >
              </fz-people>
            </div>
          </div>
          <div class="contentList" v-if="replaceForm.isWorkSheet">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">优先级</span>
            </div>
            <div class="contentRight">
              <select class="iu-select" required v-model="replaceForm.priority">
                <option :value="1" selected>一般</option>
                <option :value="2">重要</option>
                <option :value="3">紧急</option>
              </select>
            </div>
          </div>
          <div class="contentList full" v-if="replaceForm.isWorkSheet">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">描述</span>
            </div>
            <div class="contentRight">
              <textarea
                name="userQuestion"
                v-model="replaceForm.workSheetRemark"
                placeholder="请输入描述"
                class="userQuestion"
                maxlength="200"
              ></textarea>
            </div>
          </div>
        </div>
      </div>
      <div class="contentList">
        <button type="button" class="subBtn" @click="cancel">取消</button>
        <button type="button" class="subBtn" @click="eventSubmit">
          保存
        </button>
      </div>
    </div>
    <div v-transfer-dom>
      <confirm
        v-model="showConfirm"
        title="提前更换"
        @on-cancel="onCancel"
        @on-confirm="handleSubmit"
      >
        <p>
          您提交的更换设备部件，还未达到更换期限，是否确认提前更换
        </p>
      </confirm>
    </div>
  </div>
</template>

<script>
import fzPeople from "@/components/common/replace/sellWorkOrderPeople";
import DeviceDao from "@/daos/device_dao";
import SpotCheckDao from "@/daos/spotCheckDao";

import iuHeader from "@/components/common/header/index";
import FileUpload from "@/daos/file_upload";
import upload from "@/components/common/upload/upload";
import { XInput, Calendar, XSwitch, Group, Confirm, TransferDom } from "vux";
import dayjs from "dayjs";
export default {
  directives: {
    TransferDom
  },
  components: {
    fzPeople,
    iuHeader,
    upload,
    Group,
    Confirm,
    XSwitch,
    XInput
  },
  data() {
    return {
      userQuestion: "",
      listValue: 0,
      leader: "",
      departmentId: "", //部门id
      selectPeopleId: "", //处理人id
      getSelectDevice: {}, //获取设备
      showConfirm: false,
      departmentIdshow: false,
      selectPeopleIdshow: false,
      deviceIdshow: false,
      partsIdshow: false,
      value: false,
      replaceCycleUnitText: ["", "天", "周", "月", "年"],
      dueTimeUnitOption: ['','天','月','年'],
      departmentName: "",
      url: "",
      fileList: [],
      deviceData: [],
      peopleData: [],
      userServiceArea: {},
      loading: false,
      id: 0,
      isLastLevel: 0,
      edit: false,
      detail: {
        record: {},
        config: {}
      },
      backupForm: {},
      replaceForm: {
        componentId: 0,
        componentName: "",
        configId: 0,
        createEndTime: "",
        createStartTime: "",
        delayTime: "",
        endTime: "",
        departmentId: 0,
        deviceId: 0,
        id: 0,
        deviceName: "",
        isWorkSheet: 0,
        dueTime: '',
        dueTimeUnit: 1,
        operator: "",
        orgId: 0,
        pictures: "",
        priority: 1,
        remark: "",
        replaceResult: "更换完成",
        replaceType: "",
        status: "",
        workSheetLeader: "",
        workSheetRemark: "",
        onlineTime: new Date()
      },
      curDepartment: {
        departmentName: "选择部门",
        id: -1
      }
    };
  },
  //返回首页的公共方法
  inject: ["backToHomepage"],
  created() {
    this.id = this.$route.query.id || 0;
    this.isLastLevel = this.$route.query.isLastLevel || 0;
    this.departmentName = this.$route.query.departmentName || "";
    this.initDefaultForm();
  },
  computed: {
    user() {
      return this.$store.state.user;
    }
  },
  filters: {
    statusText(key) {
      let text = "";
      switch (key) {
        case 1:
          text = "未更换";
          break;
        case 3:
          text = "逾期未更换";
          break;
        case 5:
          text = "更换完成";
          break;
        case 7:
          text = "逾期完成";
          break;
        case 9:
          text = "无需更换";
          break;
        case 11:
          text = "提前更换";
          break;
        default:
          text = "未更换";
          break;
      }
      return text;
    }
  },
  methods: {
    recovery() {
      window.scroll(0, 0);
    },
    back() {
      this.$router.go(-1);
      // history.back(-1);
      // this.$route.replace()
      //   this.$router.replace(
      //     {
      //       name: "operaionManage"
      //     },
      //     () => {},
      //     () => {}
      //   );
    },
    initDefaultForm() {
      if (!this.user) {
        this.getUserInfo();
      } else {
        this.getReplaceTaskRecordConfig(this.id);
        this.getOutboundOrderUserByDepartment(this.user.serviceAreaTree.id);
        this.replaceForm.operator = this.$store.state.user.id

      }

      // this.getUserServiceArea();
    },
    initEdit() {
      if (this.id) {
        this.edit = true;
        this.getOutboundOrderDetails(this.id);
      }
    },
    getUserInfo() {
      this.$http(this.$API.getUserInfo, {}).then(res => {
        this.$store.commit("saveUser", res);
        this.initDefaultForm();
        this.replaceForm.operator = this.$store.state.user.id
        // this.receiver = this.$store.state.user.id;
        // this.receiverName = this.$store.state.user.name;
      });
    },
    getReplaceTaskRecordConfig(id) {
      DeviceDao.getReplaceTaskRecordConfig(id, res => {
        if (res.record) {
          this.detail = res;
          // if (res.config.onlineTime) {
          //   this.replaceForm.onlineTime = dayjs(res.config.onlineTime);
          // }
          this.replaceForm.dueTime = res.config.dueTime || ""
          this.replaceForm.dueTimeUnit = res.config.dueTimeUnit || 1
          this.curDepartment.id = res.record.departmentId;
          this.curDepartment.departmentName = res.record.departmentName || "";
        } else {
          this.$vux.toast.show({ text: res.description, type: "warn" });
          // this.$commom.alert(res.description || "");
          this.$router.replace(
            {
              name: "operaionManage",
              query: {
                index: 1
              }
            },
            () => {},
            () => {}
          );
        }
      });
    },

    getOperator(peopleData) {
      if (!!peopleData.id) {
        this.replaceForm.operator = peopleData.id;
      }
    },

    // 当点击完成时，获取处理人
    getPeople(peopleData) {
      if (!!peopleData.id) {
        this.replaceForm.workSheetLeader = peopleData.id;
      }
      if (!this.replaceForm.workSheetLeader) {
        this.selectPeopleIdshow = false;
      } else {
        this.selectPeopleIdshow = true;
      }
    },
    getOutboundOrderUserByDepartment(departmentId) {
      SpotCheckDao.getOutboundOrderUserByDepartment(departmentId, res => {
        if (res && res.length) {
          this.peopleData = res;
        }
      });
    },
    // 当点击完成时，获取处理人
    selectReceiver(peopleData) {
      if (!!peopleData.id) {
        this.receiver = peopleData.id;
      }
    },
    cancel() {
      this.back();
    },
    onCancel() {
      this.showConfirm = false;
    },
    eventSubmit() {
      if (this.replaceForm.replaceResult === "更换完成") {
        if (
          this.detail.record.residueTime > 0 &&
          this.detail.record.residueTime <= this.detail.config.remindTime
        ) {
          // 更换完成
          this.replaceForm.status = 5;
        } else if (
          this.detail.record.residueTime > this.detail.config.remindTime
        ) {
          // 提前更换
          this.replaceForm.status = 11;
        } else if (this.detail.record.residueTime < 0) {
          // 逾期完成
          this.replaceForm.status = 7;
        } else {
          this.replaceForm.status = 5;
        }
      } else if (this.replaceForm.replaceResult === "无需更换") {
        this.replaceForm.status = 9;
      } else if (this.replaceForm.replaceResult === "延后更换") {
        this.replaceForm.status = 1;
      }

      if (this.replaceForm.status === 11) {
        this.showConfirm = true;
      } else {
        this.handleSubmit();
      }
    },
    handleSubmit() {
      let text = "";

      if (
        this.replaceForm.replaceResult === "延后更换" &&
        !this.replaceForm.endTime
      ) {
        text = "请选择延后更换时间";
      }
      if (this.replaceForm.isWorkSheet) {
        if (!this.replaceForm.workSheetLeader) {
          text = "请选择负责人";
        }
        if (!this.replaceForm.workSheetRemark) {
          text = "请输入工单描述";
        }
      }

      if (text) {
        this.$vux.toast.show({ text, type: "warn" });
        return;
      }

      this.replaceForm.id = this.id;
      this.replaceForm.componentId = this.detail.record.componentId;
      this.replaceForm.componentName = this.detail.record.componentName;
      this.replaceForm.departmentId = this.detail.record.departmentId;
      this.replaceForm.deviceId = this.detail.record.deviceId;
      this.replaceForm.deviceName = this.detail.record.deviceName;
      this.replaceForm.orgId = this.detail.record.orgId;
      this.replaceForm.replaceType = this.detail.record.replaceType;
      this.replaceForm.pictures = this.fileList.join(",");
      this.replaceForm.configId = this.detail.record.configId;
      this.replaceForm.startTime = dayjs(
        this.detail.record.startTime || undefined
      );
      if (!this.replaceForm.endTime) {
        this.replaceForm.endTime = dayjs(
          this.detail.record.endTime || undefined
        );
      }

      // this.replaceForm.status = this.detail.config.status

      // console.log(this.replaceForm);

      DeviceDao.postReplaceTaskRecordReplace(this.replaceForm, res => {
        // 清空所有的值
        if (res === "success") {
          this.$vux.toast.show({ text: "保存成功！", type: "success" });
          this.back();
        } else {
          this.$commom.alert(res.description || "");
        }
      });
    },

    isNumber(source) {
      let flag = /^([0-9]*)$/.test(source);
      // console.log(flag,source);
      return flag;
    },
    isNumber2(source) {
      let flag = /^([0-9]*|\d*\.\d{1,2}?)$/.test(source);
      // console.log(flag,source);
      return flag;
    },
    selectTime(target) {
      let _this = this;
      this.$vux.datetime.show({
        cancelText: "取消",
        confirmText: "确定",
        format: "YYYY-MM-DD",
        startDate: "",
        onConfirm(value) {
          _this.replaceForm[target] = dayjs(value);
        },
        onHide(type) {
          if (type === "cancel") {
            // that.banci = value
          }
        }
      });
    },
    saveSellWorkOrder(obj) {
      localStorage.setItem("sellWorkOrder", JSON.stringify(obj));
    },
    getSellWorkOrder(obj) {
      let sellWorkOrder = JSON.parse(localStorage.getItem("sellWorkOrder"));
      return sellWorkOrder;
    },
    oversize() {
      this.$vux.toast.text("文件大小请不要超过5MB。");
    },
    overcount() {
      this.$vux.toast.text("文件个数请小于10个。");
    },
    deleteList(index) {
      this.fileList.splice(index, 1);
    },
    afterRead(files) {
      let formData = new FormData();
      formData.append("file", files);
      this.loading = true;
      FileUpload.upload(
        formData,
        res => {
          // console.log(res);
          this.loading = false;
          this.fileList.push(res);
        },
        err => {
          this.loading = false;
          this.$vux.toast.text(err);
        }
      );
    }
  }
};
</script>
<style lang="less">
.replace-box {
  .vux-x-switch.weui-cell_switch {
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
<style lang="less" scoped>
textarea::-webkit-input-placeholder {
  color: rgb(111, 111, 119) !important;
}
textarea:-moz-placeholder  {
  color: rgb(111, 111, 119) !important;
}

textarea::-moz-placeholder  {
  color: rgb(111, 111, 119) !important;
}
textarea:-ms-input-placeholder  {
  color: rgb(111, 111, 119) !important;
}

input {
  &::placeholder {
    font-size: 14px;
    color: gray !important;
  }
}
* {
  padding: 0;
  margin: 0;
  list-style: none;
  border: none;
}
html,
body {
  width: 100%;
}
.replace-box {
  width: 100%;
  min-height: 100vh;
  height: auto;
  background-color: #18182c;
}
.backHistory {
  transform: rotate(90deg);
  -ms-transform: rotate(90deg); /* IE 9 */
  -moz-transform: rotate(90deg); /* Firefox */
  -webkit-transform: rotate(90deg); /* Safari 和 Chrome */
  -o-transform: rotate(90deg);
  line-height: 40px;
  font-size: 25px !important;
  margin-left: 10px;
}
.pageTop {
  height: 40px;
  color: #fff;
  position: fixed;
  height: 40px;
  width: 100%;
  left: 0px;
  top: 0px;
  background-color: #22233f;
  z-index: 9;
  .sellWorkOrder_header_title {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 16px;
  }
}
.content {
  width: 100%;
  height: 100%;
  // overflow-y: auto;
  padding: 0 8px 20px;
  box-sizing: border-box;
  background-color: #18182c;
}

.cate-nfo {
  height: auto;
  // min-height: calc(~"100vh" - 80px);
  padding-bottom: 8px;
  border-radius: 8px;
  background-color: #18182c;
  .info-list {
    background: #22233f;
    padding: 8px;
    margin: 8px 0;
    // min-height: 260px;
    .info-list-item {
      display: flex;
      flex-wrap: wrap;
      margin: 8px 0;
    }
    .info-title {
      color: rgba(255, 255, 255, 0.5);
      font-size: 16px;
      // margin-right: 30px;
      width: 100px;
      text-align: right;
    }

    .info-value {
      flex: 1;
      font-size: 16px;
      color: #fff;

      .status1,
      .status4 {
        color: #4fa8e7;
      }
      .status3 {
        color: #456de6;
      }
      .status5,
      .status7,
      .status11 {
        color: #dd9710;
      }
      img {
        max-width: 100px;
        height: auto;
        margin-bottom: 8px;
        margin-right: 8px;
      }
    }
    .modify-btn {
      font-size: 14px;
      margin-left: 8px;
      color: gray;
    }
    .warning {
      color: #ff2c2c;
    }
    .modify {
      font-size: 16px;
      padding: 8px;
      color: rgba(255, 255, 255, 0.5);
    }
  }
}
.contentList {
  padding: 8px 0;
  overflow: hidden;
  // border-bottom: 1px solid #464656;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  &.full {
    flex-wrap: wrap;
    .contentRight {
      width: 100%;
      margin-top: 3px;
    }
  }
  -webkit-text-size-adjust: 100% !important;
  .err-msg {
    flex: none;
    width: 100%;
    color: #ff2c2c;
    font-size: 12px !important;
    padding-left: 35%;
    -webkit-text-size-adjust: 100% !important;
  }
}

.upload {
  display: flex;
  flex-direction: column;
  // align-items: center;
  justify-content: space-between;
}
.contentLeft,
.contentRight {
  font-size: 17px;
}
.contentLeft {
  color: #ffffff;
  flex: none;
}
.contentRight {
  position: relative;
  color: #fff;
  box-sizing: border-box;
  // margin-top: 3px;
  width: 65%;
  // display: flex;
  // justify-content: flex-end;
  &.border {
    border-bottom: 0.026667rem solid #464656;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  input {
    // text-align: right;
    touch-action: none;
    width: 86%;
    border: 0;
    color: #ffffff;
    font-size: 16px;
    margin-right: 4px;
    &.full {
      width: 100%;
    }
  }
}
.cancelPos {
  position: static;
  width: auto !important;
}
.notNull {
  color: #d81e06;
}

.userQuestion {
  font-size: 17px;
  width: 100%;
  height: 100px;
  border-radius: 6px;
  padding: 10px;
  box-sizing: border-box;
  background-color: transparent;
  border: 1px solid #747480;
  color: #fff;
  text-align: left !important;
}
.userQuestion::-webkit-input-placeholder {
  color: #6f6f77;
  text-align: left;
}
.subBtn {
  width: 40%;
  height: 40px;
  line-height: 1;
  padding: 13px 0;
  box-sizing: border-box;
  text-align: center;
  margin: 0 auto;
  border-radius: 13px;
  background-color: #456de6;
  color: #ffffff;
  margin: 0 4%;
  font-size: 17px;
  margin-top: 0;
  &.is-edited {
    color: #d2d2d2;
    background-color: gray;
  }
}
.iu-select {
  height: 26px;
  width: 100%;
  padding: 2px 4px 3px;
  border: none;
  outline: none;
  border: 1px solid #eee;
  border-radius: 2px;
  font-size: 14px;
  color: #fff;
  background: transparent;
  option {
    color: #000;
    background: rgba(255, 255, 255, 0.9);
  }
}
</style>
